from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator
from datetime import datetime,timedelta


from common.models import Users,Types,Goods,Orders,Detail

# 公共信息加载函数
def loadinfo(request):
    '''加载商品类别信息'''
    lists = Types.objects.filter(pid=0)
    context = {'typelist':lists}
    return context

def  viporders(request):
    '''浏览订单信息'''
    context = loadinfo(request)
    #获取当前登录者的订单信息
    odlist = Orders.objects.filter(uid=request.session['vipuser']['id'])

    #获取、判断并按订单状态过滤
    state = request.GET.get("state",None)
    #按订单状态过滤
    if state:
        odlist = odlist.filter(state=int(state))

    #获取、判断并按近三个月订单/所有订单过滤
    allorders = request.GET.get("all",None)
    if allorders == "1":
        #全部订单，不过滤
        pass
    else:
        #默认按近三个月的订单过滤
        now = datetime.now()
        #start = datetime(now.year,now.month,now.day)
        three_month_ago = now - timedelta(90)
        odlist = odlist.filter(addtime__gte=three_month_ago)

    #遍历订单信息，查询对应的详情信息
    for od in odlist:
        delist = Detail.objects.filter(orderid=od.id)
        #遍历订单详情，并且获取对应的商品信息（图片）
        for og in delist:
            og.picname = Goods.objects.only("picname").get(id=og.goodsid).picname
        od.detaillist = delist

    context['orderslist'] = odlist
    return render(request,"web/viporders.html",context)

def odstate(request):
    ''' 修改订单状态 '''
    try:
        oid = request.GET.get("oid",'0')
        ob = Orders.objects.get(id=oid)
        ob.state = request.GET['state']
        ob.save()
        return redirect(reverse('vip_orders'))
    except Exception as err:
        print(err)
        return HttpResponse("订单处理失败！")

def info(request):
    '''加载个人中心（我的商城）页面'''
    #获取当前登录者的用户信息
    member = Users.objects.get(id=request.session['vipuser']['id'])
    #获取当前登录者的订单信息
    odlist = Orders.objects.filter(uid=request.session['vipuser']['id'])
    #获取当前登录者的待付款订单信息
    odlist0 = odlist.filter(state=0)
    #获取当前登录者的待发货订单信息
    odlist1 = odlist.filter(state=1)
    #封装信息加载模板输出
    context = loadinfo(request)
    context['member'] = member
    context['topay_num'] = odlist0.count()
    context['todeliver_num'] = odlist1.count()
    return render(request,"web/member.html",context)

def edit(request):
    '''加载编辑会员的个人信息页面'''
    #获取当前登录者的用户信息
    user = Users.objects.get(id=request.session['vipuser']['id'])
    #封装信息加载模板输出
    context = loadinfo(request)
    context['user'] = user
    return render(request,"web/memberedit.html",context)

def update(request):
    '''执行修改会员信息'''
    context = loadinfo(request)

    try:
        #获取当前登录者的用户信息
        user = Users.objects.get(id=request.session['vipuser']['id'])
        user.name = request.POST['name']
        user.sex = request.POST['sex']
        user.address = request.POST['address']
        user.code = request.POST['code']
        user.phone = request.POST['phone']
        user.email = request.POST['email']
        user.save()
        # 个人信息修改成功，将修改后的个人信息放入到session中，并跳转页面
        request.session['vipuser'] = user.toDict()
        context['info'] = "您的个人信息修改成功！"
    except Exception as err:
        print(err)
        context['info'] = "您的个人信息修改失败！"
    return render(request,"web/memberinfo.html",context)

def resetps(request):
    '''加载重置密码表单'''
    #封装信息加载模板输出
    context = loadinfo(request)
    return render(request,"web/memberresetps.html",context)

def doresetps(request):
    '''执行重置密码'''
    context = loadinfo(request)

    try:
        #获取当前登录者的用户信息
        user = Users.objects.get(id=request.session['vipuser']['id'])

        #验证密码
        import hashlib
        m = hashlib.md5()
        m.update(bytes(request.POST['oldpassword'],encoding="utf8"))
        #验证原密码是否正确
        if user.password == m.hexdigest():
            #验证两次输入密码是否一致
            if request.POST['password'] == request.POST['repassword']:
                # 此处验证通过，更新用户密码及session信息，封装信息并跳转页面
                m = hashlib.md5()
                m.update(bytes(request.POST['password'],encoding="utf8"))
                user.password = m.hexdigest()
                user.save()
                request.session['vipuser'] = user.toDict()
                context['info'] = "重置密码成功！"
                return render(request,"web/memberinfo.html",context)
            else:
                context['info'] = "两次输入密码不一致！"
                return render(request,"web/memberresetps.html",context)
        else:
            context['info'] = "原密码有误，请重新输入！"
            return render(request,"web/memberresetps.html",context)
    except Exception as err:
        print(err)
        context['info'] = "重置密码错误！"
        return render(request,"web/memberresetps.html",context)

